<template>
  <div class="add">
    <el-form
      ref="form"
      class="form"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="商品图片" prop="image">
        <imageUpload v-model="form.image" />
      </el-form-item>
      <el-form-item label="轮播图" prop="sliderImage">
        <el-upload
          :action="uploadImgUrl"
          :file-list="filesList"
          ref="upload"
          list-type="picture-card"
          :limit="3"
          @submit.native.prevent
          :headers="headers"
          :show-file-list="true"
          :on-change="fileChange"
          :on-remove="fileRemove"
          :on-success="handleUploadSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品名" prop="name">
        <el-input v-model="form.name" placeholder="请输入商品名" />
      </el-form-item>
      <el-form-item label="商品简介">
        <editor v-model="form.info" :min-height="192" />
      </el-form-item>
      <el-form-item label="关键字" prop="keyword">
        <el-input v-model="form.keyword" placeholder="请输入关键字" />
      </el-form-item>
      <el-form-item label="分类ID" prop="cateId">
        <el-select
          v-model="form.cateId"
          placeholder="请选择分类"
          clearable
          size="small"
          style="width: 100%"
        >
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.cateName + '-' + item.id"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="parseNeedScore" label="需要积分" prop="integral">
        <el-input v-model="form.integral" placeholder="请输入需要积分" />
      </el-form-item>

      <el-form-item
        label="绿色积分"
        v-if="parseShowGreenPoints"
        prop="greenPoints"
      >
        <el-input
          v-model.number="form.greenPoints"
          placeholder="请输入绿色积分"
        />
      </el-form-item>

      <el-form-item label="商家ID" prop="storeId">
        <el-input v-model="form.storeId" placeholder="请输入商家Id" />
      </el-form-item>

      <el-form-item label="进价" prop="price">
        <el-input v-model="form.price" placeholder="请输入进价" />
      </el-form-item>
      <el-form-item label="售价" prop="vipPrice">
        <el-input v-model="form.vipPrice" placeholder="请输入售价" />
      </el-form-item>
      <el-form-item label="利润" prop="postage">
        <span class="lirun"> {{ parseLirun }} </span>
      </el-form-item>
      <el-form-item label="赠送倍数" prop="giftAmount">
        <el-input v-model="form.giftAmount" placeholder="请输入赠送倍数" />
      </el-form-item>
      <el-form-item label="销量" prop="sales">
        <el-input v-model.number="form.sales" placeholder="请输入销量" />
      </el-form-item>
      <el-form-item label="库存" prop="stock">
        <el-input v-model.number="form.stock" placeholder="请输入库存" />
      </el-form-item>

      <el-form-item label="贡献值" prop="quota">
        <el-input v-model.number="form.quota" placeholder="请输入贡献值" />
      </el-form-item>

      <el-form-item label="品牌" prop="brandId">
        <el-select
          v-model="mainBrandId"
          @change="handleMainChange"
          placeholder="请选择主品牌"
        >
          <el-option
            v-for="item in brandList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <el-select v-model="subBrandId" placeholder="请选择子品牌">
          <el-option
            v-for="item in childBrandList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>

        <span v-if="form.brandId">选中得值:{{ form.brandId }}</span>
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input v-model.number="form.sort" placeholder="请输入序号" />
      </el-form-item>
      <el-form-item label="是否事业" prop="isBiz">
        <el-switch
          v-model="form.isBiz"
          inactive-text="否"
          :inactive-value="0"
          :active-value="1"
          active-text="是"
        >
        </el-switch>
      </el-form-item>
      <el-form-item label="是否限购" prop="isLimit">
        <el-row>
          <el-col :span="8">
            <el-switch
              v-model="form.isLimit"
              inactive-text="不限"
              active-text="限购"
              :inactive-value="0"
              :active-value="1"
              active-color="#ff4949"
              inactive-color="#13ce66"
            >
            </el-switch>
          </el-col>
          <el-col :span="16" v-show="form.isLimit == 1">
            <div style="width: 20%; display: inline-block">限购数量：</div>
            <el-input
              v-model="form.limitNum"
              placeholder="请输入限购数量"
              oninput="value=value.replace(/[^\d]/g,'')"
              style="width: 80%"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="混合支付">
        <div>
          <el-switch
            v-model="isMixPay"
            inactive-text="否"
            active-text="是"
            @change="payTypeChanged"
          >
          </el-switch>
        </div>
        <el-row v-show="this.isMixPay" style="margin-top: 1%">
          <el-col :span="8" style="display: flex">
            现金比例：<el-input
              :value="form.cashRatio"
              style="width: 50%"
              :disabled="true"
            />%
          </el-col>
          <el-col :span="8" style="display: flex">
            gtfy比例：<el-input
              v-model="form.passProportion"
              style="width: 50%"
              @input="gtfyInputChanged"
            />%
          </el-col>
          <el-col :span="8" style="display: flex">
            <el-input-number
              v-model="form.passProportion"
              :min="0"
              :max="100"
              width="100"
              @change="gtfyChanged"
            ></el-input-number
            >%
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="实际支付">
        <el-row>
          <el-col :span="2" style="border: 1px solid transparent"></el-col>
          <el-col v-if="form.cashRatio" :span="7">
            <div class="actualPay" style="width: 37%">
              ￥{{ (form.vipPrice * form.cashRatio) / 100 }}
            </div>
          </el-col>
          <el-col v-else :span="7">
            <div class="actualPay" style="width: 37%">
              ￥{{ form.vipPrice }}
            </div>
          </el-col>
          <el-col :span="14">
            gtfy
            <div class="actualPay" style="width: 18%; margin-left: 3%">
              {{ (form.vipPrice * form.passProportion) / 100 }}
            </div>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item>
        <el-button class="btn" type="primary" @click="submitForm"
          >确 定</el-button
        >
      </el-form-item>

      <el-form-item>
        <el-button class="btn" @click="cancel">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import ImageUpload from "@/components/ImageUpload";
import ImagesUpload from "@/components/ImagesUpload";
import Editor from "@/components/Editor";

import {
  listProduct,
  getProduct,
  delProduct,
  addProduct,
  updateProduct,
  exportProduct,
} from "@/api/ds/product";

import { listCategory } from "@/api/ds/category";
import { getToken } from "@/utils/auth";
import SkuChoice from "./components/SkuChoice.vue";

// 引入品牌
import { brandList } from "@/api/ds/brand";
export default {
  components: {
    ImageUpload,
    ImagesUpload,
    Editor,
  },
  props: {},
  data() {
    var validateID = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*){1,3}$/.test(value)) {
          callback(new Error("请输入正确的值"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入值"));
      }
    };
    var validatePrice = (rule, value, callback) => {
      if (value) {
        if (!/^([1-9][0-9]*)+(.[0-9]{1,2})?$/.test(value)) {
          callback(new Error("请输入正确的价格（最多两位小数）"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入价格"));
      }
    };

    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadImage", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      filesList: [],
      categoryList: [], // 分类列表

      form: {},
      // 主品牌
      mainBrandId: "",
      // 子品牌
      subBrandId: "",
      brandList: [],
      childBrandList: [],
      // 表单校验
      rules: {
        image: [{ required: true, message: "商品图不能为空", trigger: "blur" }],
        sliderImage: [
          { required: true, message: "轮播图不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "商品名不能为空", trigger: "blur" }],
        cateId: [{ required: true, validator: validateID, trigger: "blur" }],
        price: [{ required: true, message: "进价不能为空", trigger: "blur" }],
        vipPrice: [
          { required: true, message: "售价不能为空", trigger: "blur" },
        ],
        sales: [{ required: true, message: "销量不能为空", trigger: "blur" }],
        stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
        quota: [{ required: true, message: "贡献值不能为空", trigger: "blur" }],
        giftAmount: [
          { required: true, message: "赠送倍数不能为空", trigger: "blur" },
        ],
        limitNum: [
          { required: true, message: "限购数量不能为空", trigger: "blur" },
        ],
      },
      isMixPay: false, // 是否混合支付
    };
  },
  computed: {
    /**
     * 解析利润
     */
    parseLirun() {
      return (
        Number.parseFloat(this.form.vipPrice) -
          Number.parseFloat(this.form.price) || "0"
      );
    },
    /**
     * 绿色积分显示
     */
    parseShowGreenPoints() {
      return this.form.cateId == 275 || this.form.cateId == "275";
    },
    /**
     * 需要积分
     */
    parseNeedScore() {
      return this.form.cateId > 100 && this.form.cateId < 200;
    },
  },
  watch: {},
  created() {
    this.getCateList();
    this.getBrandList();
  },
  methods: {
    async handleMainChange(value) {
      let mainId = value;
      let res = await brandList({ brandId: mainId });
      if (res.code === 200) {
        this.childBrandList = res.rows;
      }
    },

    payTypeChanged() {
      if (!this.isMixPay) {
        this.form.passProportion = 0;
        this.form.cashRatio = 100;
      }
    },

    gtfyInputChanged(value) {
      this.form.cashRatio = 100 - value;
    },

    gtfyChanged(value) {
      if (value) {
        this.form.passProportion = value;
        this.form.cashRatio = 100 - Number.parseFloat(value);
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.$refs.upload.clearFiles(); // 取消按钮也要清一遍轮播图
      this.reset();
      // 清理dialog form缓存
      this.$refs.skuchoice.hasSubmit = false;
    },
    submitForm() {
      if (this.form.cateId == 275) {
        this.form.passProportion = 0;
        this.form.cashRatio = 100;
        this.form.isBiz = 0;
        this.isMixPay = false;
      } else {
        this.form.greenPoints = null;
      }

      /** start 防止用户先点击限购，已经输入数量之后，再次点击不限购，limitNum会存入以前输入的数字。 */
      if (this.form.isLimit == 0) {
        this.form.limitNum = 0;
      }
      if (!this.form.isBiz) {
        this.form.isBiz = 0;
      }
      if (!this.form.storeId) {
        this.form.storeId = 0;
      }
      /** end */

      /**start  this.form.sliderImage Array转成String */
      this.form.sliderImage = [];
      for (let i = 0; i < this.filesList.length; i++) {
        if (this.filesList[i].url) {
          this.form.sliderImage.push(this.filesList[i].url);
        } else {
          this.form.sliderImage.push(this.filesList[i]);
        }
      }
      /**end  this.form.sliderImage Array转成String */

      /**start 做个判断 gtfy比例为0时 现金比例为100 为防止数据库现金比率为null而写*/
      if (this.form.passProportion == 0) this.form.cashRatio = 100;

      if (
        this.form.cateId > 100 &&
        this.form.cateId < 200 &&
        !this.form.integral
      ) {
        this.$notify({
          title: "需要填写积分",
          message: "类目在100-200之间的请填写积分",
          type: "warning",
        });

        return;
      }

      /**end 做个判断 gtfy比例为0时 现金比例为100 为防止数据库现金比率为null而写*/
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (
            (this.form.price && this.form.vipPrice) ||
            this.form.vipPrice === 0 ||
            this.form.price === 0
          ) {
            this.form.postage =
              Number.parseFloat(this.form.vipPrice) -
              Number.parseFloat(this.form.price);
          }
          this.form.sliderImage = this.form.sliderImage.toString();
          if (this.form.id != null) {
            updateProduct(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.$refs.upload.clearFiles();
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.$refs.upload.clearFiles();
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    getCateList() {
      listCategory().then((response) => {
        this.categoryList = response.rows;
      });
    },

    async getBrandList() {
      let res = await brandList({ grade: 1 });
      if (res.code === 200) {
        this.brandList = res.rows;
      }
    },

    //检测文件成功、删除 都先把原有清空，再重新赋值。
    fileRemove(file, fileList) {
      this.filesList = [];
      for (let index = 0; index < fileList.length; index++) {
        this.filesList.push(fileList[index].url);
      }
    },

    fileChange() {},

    handleUploadSuccess(response, file, fileList) {
      this.filesList = [];
      for (let index = 0; index < fileList.length; index++) {
        if (fileList[index].response) {
          this.filesList.push(fileList[index].response.url);
        } else {
          this.filesList.push(fileList[index].url);
        }
      }
    },
  },
  mounted() {},
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  deactivated() {},
};
</script>
<style lang="scss" scoped>
.add {
  width: 100%;

  .form {
    width: 800px;
    box-sizing: border-box;
    padding: 20px;
  }

  .actualPay {
    width: 33%;
    text-align: center;
    margin-left: 6%;
    display: inline-block;
    color: white;
    background: #1890ff;
    font-weight: 600;
    border-radius: 4px;
  }

  .btn {
    width: 100%;
  }

  .lirun {
    font-weight: 600;
    font-size: 18px;
  }
}
</style>
